#coding=utf-8
'''
Created on 2009-10-8

@author: James
'''
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from zhaokelai.users.models import users
from zhaokelai.common import skinFolder,checkLogin
from zhaokelai.users.views import authenticate

app_info={
            "appname":"招客来客户管理系统",
            "appversion":1.0,
            }

@checkLogin
def index(request):
    userid = request.session.get('user', None)
    user = users.objects.get(pk=userid)
    REFERER= request.GET.get('REFERER', None)
    if REFERER and (REFERER.startswith("/?") or REFERER=="/"):
        REFERER=None
    return render_to_response(skinFolder(request)+'index.html', {'app_info': app_info,'user':user,'REFERER':REFERER})

    
def login(request):
    user = request.session.get('user', None)
    if user:
        return HttpResponseRedirect('/')
    else:
        uname = request.POST.get('username', None)
        pwd= request.POST.get('password', None)
        REFERER= request.POST.get('REFERER', None) or request.GET.get('REFERER', None)
        if uname and pwd:
            user=authenticate(uname,pwd)
            if user:
                request.session['user'] = user.id
                return HttpResponseRedirect('/?REFERER='+REFERER)
            else:
                return render_to_response(skinFolder(request)+'login.html', {'error_message':'用户名或密码错误','username':uname,'password':pwd,'REFERER':REFERER})
        else:
            return render_to_response(skinFolder(request)+'login.html',{'REFERER':REFERER})
        
def logout(request):
    try:
        del request.session['user']
    except KeyError:
        pass
    return HttpResponseRedirect("/")

def start(request):
    return render_to_response(skinFolder(request)+'start.html')

    
def changeStyle(request):
    if request.method == 'POST':
        skin = request.POST.get('skin', None)
        cskin = request.session.get('skin', None)
        if skin!=cskin:
            request.session['skin']=skin
            return render_to_response('change_style.html',{'skin':skin,'refresh':True})   
    return render_to_response('change_style.html',{'skin':request.session.get('skin', None)})   